package com.huan.pdf.utils;

import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;
import java.util.Map;

/**
 * freemarker 工具类
 *
 * @author admin
 */
@Slf4j
public class FreemarkerUtils {
    /**
     * 模板文件夹路径
     */
    private static final String TEMPLATE_DIR = "/templates/ftls";
    private static final Configuration CONFIGURATION;

    static {
        CONFIGURATION = new Configuration(Configuration.VERSION_2_3_30);
        CONFIGURATION.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtils.class, TEMPLATE_DIR));
        CONFIGURATION.setDefaultEncoding("UTF-8");
        CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        CONFIGURATION.setLogTemplateExceptions(false);
        CONFIGURATION.setWrapUncheckedExceptions(true);
    }

    /**
     * 根据模板名称和数据模型生成字符串
     *
     * @param templateName 模板名称
     * @param dataModel    数据模型
     * @return 生成的字符串
     */
    public static String processTemplate(String templateName, Map<String, Object> dataModel) {
        try {
            Template template = CONFIGURATION.getTemplate(templateName);
            StringWriter writer = new StringWriter();
            template.process(dataModel, writer);
            return writer.toString();
        } catch (Exception e) {
            log.error("解析模板出现问题", e);
        }
        return "";
    }
}
